/*
 * @Author: 橘子
 * @Project_description: 改变文件
 * @Description: 代码是我抄的，不会也是真的
 */
'use strict'
const fs = require('./fs.helper')
let cwd = process.cwd() //获取当前目录
const dir = cwd + '/docs' //获取docs目录
let sidebar = {} //sidebar
let nav = [] //nav
let writeList = ['.vitepress', 'public'] //白名单
let list = fs.readDirSync(dir, true) //读取目录下所有的文件
//过滤掉.vitepress结尾的文件
let filterList = list.filter((item) => {
  return !writeList.includes(item)
})

/**
 * @description 递归读取目录下的所有文件，生成sidebar.js文件
 * @author 橘子
 * @return {void} 无返回值
 * @param obj  {object} sidebar
 * @param item {string} 文件夹名
 * @param list {array} 文件夹下的文件
 */
const fileText = (obj, item, list) => {
  let itemList = []
  let subDirs = {}

  list.forEach((i) => {
    if (!i.endsWith('.md')) return //判断i是不是.md结尾
    let pathParts = i.split('/').filter((part) => part !== '')
    let fileName = pathParts.pop()
    let text = fileName.replace('.md', '') //去除.md后缀
    let name = text.replace(/^\d+/, '') //去除前面的数字

    if (pathParts.length > 0) {
      // 处理子目录
      let currentLevel = subDirs
      let path = ''
      pathParts.forEach((part, index) => {
        path = path ? `${path}/${part}` : part
        if (!currentLevel[part]) {
          currentLevel[part] = { items: [], subDirs: {} }
        }
        currentLevel = currentLevel[part].subDirs
      })
      // 将文件添加到最后一级目录
      let lastDir = subDirs
      pathParts.forEach((part) => {
        lastDir = lastDir[part]
      })
      lastDir.items.push({ text: name, link: `/${item}/${i.replace('.md', '')}` })
    } else {
      itemList.push({ text: name, link: `/${item}/${text}` })
    }
  })

  // 处理主目录文件
  let mainItems = [{ items: itemList }]

  // 递归处理子目录结构
  const processSubDirs = (dirs) => {
    return Object.entries(dirs)
      .map(([dirName, content]) => {
        const subItems = [...content.items, ...processSubDirs(content.subDirs)]
        return {
          text: dirName,
          items: subItems.length > 0 ? subItems : undefined,
        }
      })
      .filter((dir) => dir.items && dir.items.length > 0)
  }

  // 处理所有子目录
  const subDirItems = processSubDirs(subDirs)
  if (subDirItems.length > 0) {
    mainItems.push(...subDirItems)
  }

  obj[`/${item}/`] = mainItems
}

filterList.forEach((item) => {
  //读取这个目录下所有的文件
  let res = fs.readDirDepthFileSync(dir + '/' + item, true)
  if (res.length > 0) {
    nav.push({ text: item, link: `/${item}/${res[0].replace('.md', '')}` }) //把item和res[0]放到nav中
  }
  fileText(sidebar, item, res) //调用fileText方法
})

//把这个obj写入到sidebar.js中
fs.inputFileAsync(cwd + '/docs/.vitepress/sidebar.json', JSON.stringify(sidebar, null, 4))
//修改文件下的config.js
fs.inputFileAsync(cwd + '/docs/.vitepress/nav.json', JSON.stringify(nav, null, 4))

console.log('生成成功')
